<template>
  <div
    class="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center p-4"
  >
    <div class="w-full max-w-md">
      <div class="bg-white rounded-2xl shadow-xl p-8">
        <div class="text-center mb-8">
          <h1 class="text-3xl font-bold text-gray-800 mb-2">用户登录</h1>
          <p class="text-gray-600">欢迎回来，请登录您的账户</p>
        </div>

        <!-- 登录方式切换 -->
        <el-tabs v-model="loginType" class="mb-6">
          <el-tab-pane label="手机号登录" name="phone">
            <el-form
              ref="phoneFormRef"
              :model="phoneForm"
              :rules="phoneRules"
              label-position="top"
              size="large"
            >
              <el-form-item label="手机号" prop="phone">
                <el-input
                  v-model="phoneForm.phone"
                  placeholder="请输入手机号"
                  maxlength="11"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Phone /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item label="验证码" prop="code">
                <div class="flex gap-2">
                  <el-input
                    v-model="phoneForm.code"
                    placeholder="请输入验证码"
                    maxlength="6"
                    clearable
                  >
                    <template #prefix>
                      <el-icon><Lock /></el-icon>
                    </template>
                  </el-input>
                  <el-button
                    @click="sendCode"
                    :disabled="codeCountdown > 0"
                    class="w-32"
                    type="primary"
                    plain
                  >
                    {{ codeCountdown > 0 ? `${codeCountdown}s` : "获取验证码" }}
                  </el-button>
                </div>
              </el-form-item>

              <el-button
                type="primary"
                class="w-full"
                size="large"
                :loading="loading"
                @click="handlePhoneLogin"
              >
                登录
              </el-button>
            </el-form>
          </el-tab-pane>

          <el-tab-pane label="账号密码登录" name="account">
            <el-form
              ref="accountFormRef"
              :model="accountForm"
              :rules="accountRules"
              label-position="top"
              size="large"
            >
              <el-form-item label="账号" prop="username">
                <el-input
                  v-model="accountForm.username"
                  placeholder="请输入账号"
                  clearable
                >
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item label="密码" prop="password">
                <el-input
                  v-model="accountForm.password"
                  :type="showPassword ? 'text' : 'password'"
                  placeholder="请输入密码"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                  <template #suffix>
                    <el-icon
                      @click="showPassword = !showPassword"
                      class="cursor-pointer"
                    >
                      <View v-if="showPassword" />
                      <Hide v-else />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <div class="flex justify-between items-center mb-6">
                <el-checkbox v-model="rememberMe">记住我</el-checkbox>
                <a href="#" class="text-blue-600 hover:text-blue-800 text-sm"
                  >忘记密码？</a
                >
              </div>

              <el-button
                type="primary"
                class="w-full"
                size="large"
                :loading="loading"
                @click="handleAccountLogin"
              >
                登录
              </el-button>
            </el-form>
          </el-tab-pane>
        </el-tabs>

        <div class="text-center mt-6">
          <p class="text-gray-600">
            还没有账号？
            <a
              href="/login/register"
              class="text-blue-600 hover:text-blue-800 font-medium"
            >
              立即注册
            </a>
          </p>
        </div>

        <!-- 第三方登录 -->
        <div class="mt-8">
          <div class="relative">
            <div class="absolute inset-0 flex items-center">
              <div class="w-full border-t border-gray-300"></div>
            </div>
            <div class="relative flex justify-center text-sm">
              <span class="px-2 bg-white text-gray-500">其他登录方式</span>
            </div>
          </div>

          <div class="mt-6 flex justify-center space-x-4">
            <el-button circle size="large">
              <el-icon><ChatDotRound /></el-icon>
            </el-button>
            <el-button circle size="large">
              <el-icon><Message /></el-icon>
            </el-button>
            <el-button circle size="large">
              <el-icon><Star /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import {
  User,
  Lock,
  Phone,
  View,
  Hide,
  ChatDotRound,
  Message,
  Star,
} from "@element-plus/icons-vue";

definePageMeta({
  layout: false,
});

useHead({
  title: "用户登录",
});

// 登录类型
const loginType = ref<"phone" | "account">("phone");

// 表单引用
const phoneFormRef = ref();
const accountFormRef = ref();

// 手机号登录表单
const phoneForm = reactive({
  phone: "",
  code: "",
});

// 账号密码登录表单
const accountForm = reactive({
  username: "",
  password: "",
});

// 其他状态
const loading = ref(false);
const showPassword = ref(false);
const codeCountdown = ref(0);
const rememberMe = ref(false);

// 手机号验证规则
const phoneRules = {
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { pattern: /^\d{6}$/, message: "验证码格式不正确", trigger: "blur" },
  ],
};

// 账号密码验证规则
const accountRules = {
  username: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 3, max: 20, message: "账号长度在 3 到 20 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" },
  ],
};

// 发送验证码
const sendCode = async () => {
  await phoneFormRef.value?.validateField("phone");

  if (phoneRules.phone[1].pattern.test(phoneForm.phone)) {
    codeCountdown.value = 60;
    const timer = setInterval(() => {
      codeCountdown.value--;
      if (codeCountdown.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);

    ElMessage.success("验证码已发送");
  }
};

// 手机号登录
const handlePhoneLogin = async () => {
  if (!phoneFormRef.value) return;

  await phoneFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      try {
        await new Promise((resolve) => setTimeout(resolve, 1500));
        ElMessage.success("登录成功！");
        await navigateTo("/");
      } catch (error) {
        ElMessage.error("登录失败，请重试");
      } finally {
        loading.value = false;
      }
    }
  });
};

// 账号密码登录
const handleAccountLogin = async () => {
  if (!accountFormRef.value) return;

  await accountFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      try {
        await new Promise((resolve) => setTimeout(resolve, 1500));
        ElMessage.success("登录成功！");
        await navigateTo("/");
      } catch (error) {
        ElMessage.error("登录失败，请重试");
      } finally {
        loading.value = false;
      }
    }
  });
};
</script>

<style scoped>
:deep(.el-tabs__nav-scroll) {
  display: flex;
  justify-content: center;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-tabs__active-bar) {
  background-color: #667eea;
}

:deep(.el-tabs__item.is-active) {
  color: #667eea;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

:deep(.el-button--primary:hover) {
  opacity: 0.9;
}

:deep(.el-button--primary.is-plain) {
  color: #667eea;
  border-color: #667eea;
}

:deep(.el-button--primary.is-plain:hover) {
  background: #667eea;
  color: white;
}
</style>
